#define STB_IMAGE_IMPLEMENTATION

#include "stb_image.h"

class Texture {
public:
    const int32_t width = 0;
    const int32_t height = 0;
    const int32_t nrChannels = 0;
    /**
     * OpenGL 上的texture句柄
     */
    const uint32_t texture = 0;

    /**
     * 是否加载成功
     */
    bool IsLoaded() const {return isLoad;}
public:
    explicit Texture(const std::string& path) {
        stbi_set_flip_vertically_on_load(true);
        this->data = stbi_load(path.c_str(), const_cast<int32_t*>(&width), const_cast<int32_t*>(&height), const_cast<int32_t*>(&nrChannels), 0);
        if(data != nullptr) {
            glGenTextures(1, const_cast<uint32_t*>(&texture));
            glBindTexture(GL_TEXTURE_2D, texture);

            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
            glGenerateMipmap(GL_TEXTURE_2D);
            isLoad = true;
        }else {
            isLoad = false;
        }
    }

    void Use(int32_t uint) {
        glActiveTexture(uint);
        glBindTexture(GL_TEXTURE_2D, texture);
    }
private:
    /**
     * 图像数据
     */
    unsigned char * data = nullptr;
    /**
    * 是否加载成功
    */
    bool isLoad;

    ~Texture() {
        stbi_image_free(data);
    }
};